<template>
  <div class="rule-test-container">
    <div class="content-wrapper">
      <h2>规则测试</h2>

      <!-- 规则场景查询 -->
      <div class="section">
        <h3>请输入规则场景</h3>
        <el-select
          v-model="selectedScenario"
          placeholder="请选择规则场景"
          @change="handleScenarioChange"
          clearable
        >
          <el-option
            v-for="item in scenariosList"
            :key="item.key"
            :label="item.value"
            :value="item.key"
          />
        </el-select>
      </div>

      <!-- 测试数据 -->
      <div class="section" v-if="selectedScenario">
        <h3>测试数据</h3>
        <div class="test-data-container">
          <div class="field-list">
            <div
              v-for="(field, index) in modelFields"
              :key="index"
              class="field-item"
            >
              <div class="field-label">{{ field.fieldName }}</div>
              <el-input
                v-model="testData[field.modelFieldName]"
                :placeholder="`请输入${field.fieldName}`"
              />
            </div>
          </div>
        </div>
      </div>

      <!-- 测试按钮 -->
      <div class="section" v-if="selectedScenario">
        <el-button type="primary" @click="handleTest" :loading="loading"
          >测试</el-button
        >
      </div>

      <!-- 命中规则 -->
      <div class="section" v-if="matchedRules.length > 0">
        <h3>命中规则</h3>
        <div class="matched-rules">
          <el-card
            v-for="(rule, index) in matchedRules"
            :key="index"
            class="matched-rule-card"
          >
            <template #header>
              <div class="card-header">
                <span>规则名称: {{ rule.ruleName }}</span>
              </div>
            </template>
            <div>
              <div class="rule-description">{{ rule.description }}</div>
              <div class="rule-details">
                <div class="rule-results">
                  <h4>规则结果:</h4>
                  <div
                    v-for="(result, rIdx) in rule.resultDetail"
                    :key="rIdx"
                    class="rule-result-item"
                  >
                    <span
                      >{{ result.fieldName }}: {{ result.targetValue }}</span
                    >
                  </div>
                </div>
              </div>
            </div>
          </el-card>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from "vue";
import { ElMessage } from "element-plus";
import {
  getAllRuleScenariosOptions,
  getBusinessModelFields,
  executeRuleMatch,
} from "@/api/ruleTest";
import type { FieldInfo, RuleInfo, SelectOption } from "@/types";

// 规则场景列表
const scenariosList = ref<SelectOption[]>([]);
// 选中的规则场景
const selectedScenario = ref("");
// 业务模型字段
const modelFields = ref<FieldInfo[]>([]);
// 测试数据
const testData = reactive<Record<string, any>>({});
// 加载状态
const loading = ref(false);
// 命中的规则
const matchedRules = ref<RuleInfo[]>([]);

// 获取规则场景列表
const getScenariosList = async () => {
  try {
    const res = await getAllRuleScenariosOptions();
    console.log("接口返回数据:", res);
    if (res.data && res.data.code === 200) {
      // 根据接口返回数据结构进行处理
      scenariosList.value = res.data.content || [];
      console.log("规则场景列表:", scenariosList.value);
    } else {
      const errorMsg = res.data?.msg || "获取规则场景失败";
      ElMessage.error(errorMsg);
    }
  } catch (error) {
    console.error("获取规则场景失败", error);
    ElMessage.error("获取规则场景失败");
  }
};

// 场景变更
const handleScenarioChange = async (value: string) => {
  if (!value) {
    modelFields.value = [];
    Object.keys(testData).forEach((key) => delete testData[key]);
    matchedRules.value = [];
    return;
  }

  try {
    // 获取业务模型字段
    const res = await getBusinessModelFields(value);
    console.log("获取业务模型字段返回:", res);
    if (res.data && res.data.code === 200) {
      modelFields.value = res.data.data || [];
      // 重置测试数据
      Object.keys(testData).forEach((key) => delete testData[key]);
      // 初始化测试数据对象
      modelFields.value.forEach((field) => {
        testData[field.modelFieldName] = "";
      });
    } else {
      const errorMsg = res.data?.msg || "获取业务模型字段失败";
      ElMessage.error(errorMsg);
    }
    // 清空匹配结果
    matchedRules.value = [];
  } catch (error) {
    console.error("获取业务模型字段失败", error);
    ElMessage.error("获取业务模型字段失败");
  }
};

// 执行测试
const handleTest = async () => {
  // 检查是否有空值
  const emptyFields = modelFields.value.filter(
    (field) =>
      !testData[field.modelFieldName] && testData[field.modelFieldName] !== 0
  );
  if (emptyFields.length > 0) {
    ElMessage.warning(
      `请输入${emptyFields.map((f) => f.fieldName).join("、")}的值`
    );
    return;
  }

  loading.value = true;
  try {
    const requestData = {
      scenariosKey: selectedScenario.value,
      facts: testData,
    };
    console.log("发送测试数据:", requestData);

    const res = await executeRuleMatch(requestData);
    console.log("匹配结果返回:", res);
    if (res.data && res.data.code === 200) {
      matchedRules.value = res.data.data || [];
      if (matchedRules.value.length === 0) {
        ElMessage.info("未匹配到规则");
      }
    } else {
      const errorMsg = res.data?.msg || "规则匹配失败";
      ElMessage.error(errorMsg);
    }
  } catch (error) {
    console.error("规则匹配失败", error);
    ElMessage.error("规则匹配失败");
  } finally {
    loading.value = false;
  }
};

onMounted(() => {
  getScenariosList();
});
</script>

<style scoped>
.rule-test-container {
  margin: 0 auto;
  padding: 15px;
}

.content-wrapper {
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  padding: 20px;
}

.rule-test-container h2 {
  font-size: 22px;
  color: #303133;
  margin-bottom: 20px;
  border-left: 4px solid #409eff;
  padding-left: 10px;
}

.section {
  margin-bottom: 30px;
}

.section h3 {
  font-size: 18px;
  color: #606266;
  margin-bottom: 15px;
}

.test-data-container {
  border: 1px solid #ebeef5;
  border-radius: 4px;
  padding: 20px;
  background-color: #f8f9fa;
}

.field-list {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 15px;
}

.field-item {
  display: flex;
  flex-direction: column;
  gap: 5px;
}

.field-label {
  font-weight: bold;
  color: #606266;
}

.matched-rules {
  display: grid;
  gap: 15px;
}

.matched-rule-card {
  margin-bottom: 10px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-weight: bold;
}

.rule-description {
  color: #606266;
  margin-bottom: 10px;
}

.rule-details {
  margin-top: 10px;
}

.rule-results {
  margin-top: 10px;
}

.rule-result-item {
  margin: 5px 0;
  padding: 5px;
  background-color: #f8f9fa;
  border-radius: 4px;
}
</style>
